<template>
	<view class="UserCenter bigestBox boxSize_bb">
		<view class="box">
			<view class="item flex_jcsb boxSize_bb">
				<view class="item_left">
					头像
				</view>
				<view class="item_right avatar-upload" @tap="isChgImg">
					<view class="avatar-container">
						<image
							v-if="formItem.avatar"
							:src="formItem.avatar"
							mode="aspectFill"
							class="avatar-image"
						/>
						<text v-else class="upload-text">上传</text>
					</view>
				</view>
			</view>
			<view class="item flex_jcsb boxSize_bb">
				<view class="item_left">
					昵称
				</view>
				<view class="item_right">
					<input
						auto-blur
						class="uni-input"
						type="nickname"
						v-model="formItem.nickname"
					/>
				</view>
			</view>
			<view class="item flex_jcsb boxSize_bb">
				<view class="item_left">
					性别
				</view>
				<view class="item_right">
					<picker @change="changePicker" :value="getSexIndex(formItem.sex)" :range="genderLabels">
						<view class="uni-input">{{genderLabels[getSexIndex(formItem.sex)]}}</view>
					</picker>
				</view>
			</view>
			<view class="form-item submit">
				<button type="default" @tap="submit">提交</button>
			</view>
		</view>
	</view>
</template>

<script>
import { chooseFile, chooseImage, showModal, showToast, uploadFile } from '../../utils/promise';
import { updateUserInfo } from '../../api/user';
import { BASE_URL } from '../../utils/request';

	export default {
		data() {
			// 定义性别相关常量
			const GENDER = {
				MALE: {
					VALUE: "1",
					LABEL: "男",
					INDEX: 0
				},
				FEMALE: {
					VALUE: "2",
					LABEL: "女",
					INDEX: 1
				}
			};

			// 从常量生成数组
			const genderValues = [GENDER.MALE.VALUE, GENDER.FEMALE.VALUE];
			const genderLabels = [GENDER.MALE.LABEL, GENDER.FEMALE.LABEL];

			return {
				userInfo: {},
				formItem: {
					sex: GENDER.MALE.VALUE // 默认为男
				},
				gender: GENDER, // 性别常量
				genderValues, // 性别值数组
				genderLabels, // 性别标签数组
				isChange: 0,
			};
		},
		onShow() {
			this.token = uni.getStorageSync("userToken")
			if(!this.token) {
				showToast({
					title: "请登陆后再访问此页面"
				})
				return
			}
			this.userInfo = uni.getStorageSync("userInfo")
			this.formItem = {...this.formItem, ...this.userInfo}
			
			// 确保sex是有效值
			if(!this.genderValues.includes(this.formItem.sex)) {
				this.formItem.sex = this.gender.MALE.VALUE
			}
		},
		methods: {
			// 根据sex值获取在genderLabels数组中的索引
			getSexIndex(sex) {
				return sex === this.gender.FEMALE.VALUE 
					? this.gender.FEMALE.INDEX 
					: this.gender.MALE.INDEX;
			},
			changePicker(e) {
				// 将选择的索引转换为对应的性别值
				const index = Number(e.detail.value);
				this.formItem.sex = this.genderValues[index];
			},
			isChgImg() {
				chooseImage({
					count: 1,
				}).then((res) => {
					uni.showLoading({title: '上传中...'})
					const header = {
						"Authorization": `Bearer ${uni.getStorageSync("userToken")}`,
						'X-Client-Type': 'MINI_PROGRAM',
					}
					uploadFile({
						url: `${BASE_URL}/api/file/upload`,
						filePath: res.tempFilePaths[0],
						header: header,
						name: "file",
						formData: {
							'fileClassification': 'AVATAR',
						},
					}).then(uploadRes => {
						const {code, data, msg} = JSON.parse(uploadRes.data)
						uni.hideLoading()
						if(code === 200) {
							this.formItem.avatar = data
							showToast({
								title: '头像上传成功'
							})
						} else {
							showToast({
								title: msg || '上传失败'
							})
						}
					}).catch(err => {
						uni.hideLoading()
						console.log(err)
						showToast({
							title: '上传失败'
						})
					})
				}).catch((err) => {
					console.log(err)
				})
			},
			submit() {
				// 验证表单数据
				if (!this.formItem.nickname) {
					showToast({
						title: '请输入昵称'
					})
					return
				}
				
				// 显示加载中
				uni.showLoading({
					title: '提交中...'
				})
				
				// 调用接口更新用户信息
				updateUserInfo(this.formItem).then(res => {
					uni.hideLoading()
					if (res.code === 200) {
						// 使用vuex的action更新用户信息
						this.$store.dispatch('getUserInfo')
						
						showToast({
							title: '更新成功'
						})
						
						// 返回上一页
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						showToast({
							title: res.msg || '更新失败'
						})
					}
				}).catch(err => {
					uni.hideLoading()
					console.error(err)
					showToast({
						title: '更新失败'
					})
				})
			}
		}
	}
</script>

<style lang="less" scoped>
	@import "../../static/commonStyleLess/grayBox.less";

	.UserCenter {
		padding: 30rpx;
		font-family: 'PingFang SC';
		font-weight: 400;
		font-size: 28rpx;
		letter-spacing: 0px;

		.box {
			border-radius: 30rpx;

			.item {
				padding: 20rpx;
				height: 120rpx;
				border-bottom: 0.2rpx solid rgba(229, 229, 229, 1);
				align-items: center;
				box-sizing: border-box;
				display: flex;
			}
			
			.item_left {
				font-size: 28rpx;
				color: #333333;
				font-weight: 500;
			}
			
			.item_right {
				height: 90rpx;
				display: flex;
				align-items: center;
				color: #666666;
			}
			
			.avatar-upload {
				position: relative;
				
				.avatar-container {
					width: 70rpx;
					height: 70rpx; 
					border-radius: 35rpx;
					border: 1px solid #eee;
					background-color: #f5f5f5;
					display: flex;
					align-items: center;
					justify-content: center;
					overflow: hidden;
					margin: 10rpx 0;
					
					.avatar-image {
						width: 100%;
						height: 100%;
						object-fit: cover;
					}
					
					.upload-text {
						font-size: 16rpx;
						color: #999999;
						text-align: center;
						padding: 0 6rpx;
					}
				}
				
				&:active {
					opacity: 0.8;
				}
			}
			
			.submit {
				background-color: transparent;
				padding: 100rpx 0;
				width: 80%;
				position: absolute;
				bottom: 0;
				left: 50%;
				transform: translateX(-50%);
				place-content: center;
				place-items: center;
				button {
					background-color: rgb(15, 76, 151);
					color: white;
					border-radius: 60rpx;
					width: 100%;
				}
			}
			.uni-input {
				height: 90rpx;
				line-height: 90rpx;
				font-size: 28rpx;
				color: #666666;
				text-align: right;
			}
		}
	}
</style>